﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class Rep_1CSaleReportInterfaceBusiness_旧 : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters { get; set; }
        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption insertOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public Base_InterfaceOption deleteOption { get; set; }
        public Rep_1CSaleReportInterfaceBusiness_旧()
        {
            this.InterfaceName = "1C销售月收入报表";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);
            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {

                SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:K3ConnectionString");
                List<View_Rate> KD_Rate = SqlDb.GetListBySql<View_Rate>(@$"SELECT * FROM  V_WW_BD_Rate(NOLOCK) WHERE 汇率类型 = '俄罗斯专用' ");

                string dateTo = DateTime.Now.AddMonths(-queryOption.ExcInterval).ToString("yyyy-MM") + "-01";
                //获取收款单
                SalesInvoiceInterfaceBusiness saleInvoice = new SalesInvoiceInterfaceBusiness();
                saleInvoice.Filters.Clear();
                saleInvoice.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d14fd5cd44971bbf2f88cd", DataType = 15, SpliceType = 1, FilterType = 14, Value = dateTo });//FDATE字段过滤日开
                List<SalesInvoice> saleInvList = await saleInvoice.QueryAsync<SalesInvoice>(saleInvoice.queryOption, saleInvoice.tableField, saleInvoice.SqlDb);

                //获取销售出库单
                SaleOutboundInterfaceBusiness saleOutbound = new SaleOutboundInterfaceBusiness();
                var fDate = saleInvList.Where(x => !x.paymentDate.IsNullOrEmpty()).OrderBy(x => x.paymentDate.ToDateTime()).First().paymentDate.ToDateTime().ToString("yyyy-MM-dd");
                saleOutbound.Filters.Clear();
                saleOutbound.Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67c50f3a9e0bc69bf125cfcc", DataType = 15, SpliceType = 1, FilterType = 14, Value = fDate });//FDATE字段过滤日开
                List<SaleOutbound> saleOut = await saleOutbound.QueryAsync<SaleOutbound>(saleOutbound.queryOption, saleOutbound.tableField, saleOutbound.SqlDb);

                //生成源数据
                List<Rep_1CSaleReport> sourceData = new List<Rep_1CSaleReport>();
                foreach (var item in saleInvList)
                {
                    Rep_1CSaleReport rep = new Rep_1CSaleReport();
                    double rate = 0;
                    double KD_rate = 0;
                    if (!item.paymentNO.IsNullOrEmpty())
                    {
                        var saleOutRow = saleOut.Where(x => x.number == item.paymentNO && x.date.ToDateTime().ToString("yyyy-MM-dd") == item.paymentDate.ToDateTime().ToString("yyyy-MM-dd"));
                        rate = !saleOutRow.IsNullOrEmpty() && saleOutRow.Count() > 0 && !saleOutRow.First().exchangeRate.IsNullOrEmpty() ? saleOutRow.First().exchangeRate.ToDouble() : 0;
                    }
                    if (rate == 0)
                    {
                        var KD_rate_ = KD_Rate.Where(x => x.生效时间.ToDateTime().ToString("yyyy-MM-dd").ToDateTime() <= item.date.ToDateTime().ToString("yyyy-MM-dd").ToDateTime() && item.date.ToDateTime() <= x.失效时间.ToDateTime().ToString("yyyy-MM-dd").ToDateTime());

                        var RA = KD_rate_.First().汇率.ToDouble().ToString("F2").ToDouble();
                        KD_rate = !KD_rate_.IsNullOrEmpty() && KD_rate_.Count() > 0 ? (1 / KD_rate_.First().汇率.ToDouble()).ToString("F2").ToDouble() : 0;
                    }
                    rep.id = item.rowId;
                    rep.number = item.number;
                    rep.rate = rate > 0 ? rate.ToString() : KD_rate.ToString();
                    rep.rateType = rate > 0 ? "1C" : "金蝶";
                    rep.date = item.date;
                    rep.counterparty = item.counterparty;
                    rep.productName = item.productName;
                    rep.productNo = item.productNo;
                    rep.qty = item.qty;
                    rep.unit = item.unit;
                    rep.unitPrice = rate > 0 ? (item.unitPrice.ToDouble() / rate).ToString("F2") : (item.unitPrice.ToDouble() / KD_rate).ToString("F2");
                    rep.sum = rate > 0 ? (item.sum.ToDouble() / rate).ToString("F2") : (item.sum.ToDouble() / KD_rate).ToString("F2");
                    rep.valueAddedTax = rate > 0 ? (item.valueAddedTax.ToDouble() / rate).ToString("F2") : (item.valueAddedTax.ToDouble() / KD_rate).ToString("F2");
                    rep.unitPrice_s = item.unitPrice;
                    rep.sum_s = item.sum;
                    rep.tax = item.tax;
                    rep.valueAddedTax_s = item.valueAddedTax;
                    sourceData.Add(rep);
                    //rep.tax = item.tax;
                    //rep.valueAddedTax = rate > 0 ? (item.valueAddedTax.ToDouble() / rate).ToString("F2") : rep.valueAddedTax;
                }



                //获取目标数据
                fDate = saleInvList.Where(x => !x.date.IsNullOrEmpty()).OrderBy(x => x.date.ToDateTime()).First().date.ToDateTime().ToString("yyyy-MM-dd");
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d28967cd44971bbf4ded09", DataType = 15, SpliceType = 1, FilterType = 14, Value = fDate }//FDATE字段过滤日开
            );
                List<Rep_1CSaleReport> targetData = await QueryAsync<Rep_1CSaleReport>(queryOption, tableField, SqlDb);

                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<Rep_1CSaleReport> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<Rep_1CSaleReport>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<Rep_1CSaleReport> insertItem = sourceData.Except(targetData, new ComparerFromKey<Rep_1CSaleReport>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<Rep_1CSaleReport> deleteItem = targetData.Except(sourceData, new ComparerFromKey<Rep_1CSaleReport>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
